import { rejects } from "assert"

class Request {
    constructor(parms) {
        this.baseURL = "https://admin.flame-bear.com/api/"
    }
    async get(url, data) {
        return this.request('GET', url, data)
    }
    async post(url, data) {
        return this.request('POST', url, data)
    }
    async put(url, data) {
        return this.request('PUT', url, data)
    }
    async request(method, url, data) {
        const vm = this
		const token = uni.getStorageSync('dbToken') || ''
		return new Promise((resolve, reject) => {
			uni.request({
				url: vm.baseURL + url,
				data,
				method: method,
				header: {
					'content-type': 'application/x-www-form-urlencoded',
					'token': url.match('device/login') ? '' : token
				},
				success: (res) => {
					console.log(res.data)
					if (res.statusCode === 200 || res.statusCode === 204 || res.statusCode === 201) {
						if (res.data.code == 1) {
							resolve(res.data.data)
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: "none"
							})
							reject(res.data)
						}
					} else if (res.statusCode == 401) {
						toLogin()
					} else {
						// handleError(error.statusCode, url)
						checkNetWork()
						reject()
					}
				},
				fail: (error) => {
					console.error(error)
					uni.showToast({
						title: "系统繁忙，请稍后再试!",
						icon: 'none'
					})
					checkNetWork()
					reject(error)
				}
			})
		})
	   
    }
}

const errText = {
    403: "请先登录",
    401: "请先登录!",
    404: "请求的资源不存在!",
    500: "系统出现异常，请稍后再试!"
}
const checkNetWork = function() {
	uni.getNetworkType({
		success: function (res) {
			uni.hideLoading()
			if (res.networkType === 'none') {
				uni.showToast({
					title: "无网络，请打开网络设置",
					icon: "none"
				})
			}
			if (['2g','3g'].includes(res.networkType)) {
				uni.showToast({
					title: "网络情况较差",
					icon: "none"
				})
			}
		}
	});
}
function handleError(errno, url) {
    if (errno === 401) {
        // 先清除本地缓存
        // setTimeout(() => {
        //     uni.navigateTo({
        //         url: '/pages/login/index'
        //     })
        // }, 500)
    }
}
// 简陋版屏蔽二次点击事件重复触发
const debounceEvent = (fn, wait = 500) => {
	let timer = null
	return function() {
		var context = this
		var args = arguments
		if (timer) return
		fn.apply(context, args);
		timer = setTimeout(() => {
			timer = null
			clearTimeout(timer)
		}, wait)
	}
}
const toLogin = debounceEvent(function() {
	console.warn("token过期")
	uni.showToast({
		title: '登入过期，请重新登入',
		icon: "none"
	})
	setTimeout(() => {
		uni.switchTab({
			url: '/pages/member/member'
		})
	}, 1500)
	
}, 5000)

const request = new Request()
export default request;